
function Axios(config) {
  this.config = config
}
//发送请求
Axios.prototype.request = function (config) {
  let promise = Promise.resolve(config)
  let charn = [dispatchRequest, undefined] //undefined是占位符
  promise = promise.then(charn[0], charn[1])
  return promise
}
Axios.prototype.get = function (config) {
  return this.request(config)
}
Axios.prototype.post = function (config) {
  return this.request(config)
}

function dispatchRequest(config) {
  return xhrAdapter(config).then((response) => {
    return response
  }).catch((error) => {
    console.log(error);
  })
}
//适配器
function xhrAdapter(config) {
  return new Promise((resolve, reject) => {
    //发送ajax请求
    let xhr = new XMLHttpRequest()
    //初始化
    xhr.open(config.method, config.url)
    //发送
    xhr.send()
    //绑定事件
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          //成功
          resolve({
            //配置对象
            config,
            //响应体
            data: xhr.response,
            //响应头
            headers: xhr.getAllResponseHeaders(),
            //xhr请求对象
            request: xhr,
            //响应状态码
            status: xhr.status,
            //响应状态字符串
            statusText: xhr.statusText
          })
        } else {
          //失败
          reject(new Error("请求失败,响应状态码是" + xhr.status))
        }
      }
    }
    if (config.cancelToken) {
      config.cancelToken.promise.then(res => {
        xhr.abort()
      })
    }

  })
}
function CancelToken(callback) {
  let resolvecack
  this.promise = new Promise(resolve => {
    resolvecack = resolve
  })
  callback(function () {
    resolvecack()
  })
}
const context = new Axios({})
let axios = Axios.prototype.request.bind(context)
let cancel
const btnDom = document.querySelectorAll("button")
btnDom[0].onclick = function () {
  axios({
    method: "get",
    url: 'http://localhost:3000/posts',
    cancelToken: new CancelToken(function (c) {
      cancel = c
    })
  }).then(res => {
    console.log(res, 300
    );
  }, err => {
    console.log(err);
  })
}
btnDom[1].onclick = function () {
  cancel()
}
